<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="(value) => emit('update:visible', value)"
    :title="isView ? '查看设备维护' : (formData ? '编辑设备维护' : '新增设备维护')"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      :disabled="isView"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="维护编号" prop="code">
            <el-input v-model="form.code" placeholder="请输入维护编号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备名称" prop="equipmentName">
            <el-input v-model="form.equipmentName" placeholder="请输入设备名称" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备类型" prop="type">
            <el-select
              v-model="form.type"
              placeholder="请选择设备类型"
              style="width: 100%"
            >
              <el-option label="闸门设备" value="gate" />
              <el-option label="泵站设备" value="pump" />
              <el-option label="监测设备" value="monitor" />
              <el-option label="通信设备" value="communication" />
              <el-option label="电气设备" value="electrical" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备型号" prop="model">
            <el-input v-model="form.model" placeholder="请输入设备型号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="安装位置" prop="location">
            <el-input v-model="form.location" placeholder="请输入安装位置" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维护状态" prop="status">
            <el-select
              v-model="form.status"
              placeholder="请选择维护状态"
              style="width: 100%"
            >
              <el-option label="正常" value="normal" />
              <el-option label="维护中" value="maintaining" />
              <el-option label="故障" value="fault" />
              <el-option label="停用" value="stopped" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="维护日期" prop="maintenanceDate">
            <el-date-picker
              v-model="form.maintenanceDate"
              type="date"
              placeholder="请选择维护日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="下次维护日期" prop="nextMaintenanceDate">
            <el-date-picker
              v-model="form.nextMaintenanceDate"
              type="date"
              placeholder="请选择下次维护日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="维护人员" prop="maintainer">
            <el-input v-model="form.maintainer" placeholder="请输入维护人员姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="维护公司" prop="company">
            <el-input v-model="form.company" placeholder="请输入维护公司" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维护费用(元)" prop="cost">
            <el-input-number
              v-model="form.cost"
              :precision="2"
              :min="0"
              :max="1000000"
              placeholder="请输入维护费用"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="维护内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="3"
          placeholder="请输入维护内容"
        />
      </el-form-item>

      <el-form-item label="维护结果" prop="result">
        <el-input
          v-model="form.result"
          type="textarea"
          :rows="3"
          placeholder="请输入维护结果"
        />
      </el-form-item>

      <el-form-item label="发现问题" prop="problem">
        <el-input
          v-model="form.problem"
          type="textarea"
          :rows="3"
          placeholder="请输入发现的问题"
        />
      </el-form-item>

      <el-form-item label="改进建议" prop="suggestion">
        <el-input
          v-model="form.suggestion"
          type="textarea"
          :rows="3"
          placeholder="请输入改进建议"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-if="!isView" type="primary" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  visible: boolean
  formData?: any
  isView?: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = withDefaults(defineProps<Props>(), {
  formData: null,
  isView: false
})

const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()

// 表单数据
const form = reactive({
  code: '',
  equipmentName: '',
  type: '',
  model: '',
  location: '',
  status: '',
  maintenanceDate: '',
  nextMaintenanceDate: '',
  maintainer: '',
  phone: '',
  company: '',
  cost: null,
  content: '',
  result: '',
  problem: '',
  suggestion: '',
  remark: ''
})

// 表单验证规则
const rules: FormRules = {
  code: [
    { required: true, message: '请输入维护编号', trigger: 'blur' }
  ],
  equipmentName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择设备类型', trigger: 'change' }
  ],
  model: [
    { required: true, message: '请输入设备型号', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入安装位置', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择维护状态', trigger: 'change' }
  ],
  maintenanceDate: [
    { required: true, message: '请选择维护日期', trigger: 'change' }
  ],
  maintainer: [
    { required: true, message: '请输入维护人员姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  company: [
    { required: true, message: '请输入维护公司', trigger: 'blur' }
  ],
  cost: [
    { required: true, message: '请输入维护费用', trigger: 'blur' }
  ]
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    code: '',
    equipmentName: '',
    type: '',
    model: '',
    location: '',
    status: '',
    maintenanceDate: '',
    nextMaintenanceDate: '',
    maintainer: '',
    phone: '',
    company: '',
    cost: null,
    content: '',
    result: '',
    problem: '',
    suggestion: '',
    remark: ''
  })
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    if (props.formData) {
      Object.assign(form, props.formData)
    } else {
      resetForm()
    }
  }
})

// 模拟API - 保存设备维护数据
const saveEquipmentMaintenance = async (data: any) => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success(props.formData ? '更新成功' : '新增成功')
    return true
  } catch (error) {
    ElMessage.error('保存失败')
    return false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  const success = await saveEquipmentMaintenance(form)
  if (success) {
    emit('success')
    handleClose()
  }
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>